<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/22
 * Time: 13:38
 */

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/19
 * Time: 17:07
 * * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */


namespace app\home\controller;

use app\admin\model\MessageTemplate;
use app\home\model\AmountLog;
use app\home\model\Config;
use app\home\model\GoodsDiscount;
use app\home\model\GoodsOrder;
use app\home\model\IntegralLog;
use app\home\model\Level;
use app\home\model\PackageOrder;
use app\home\model\Recharge;
use app\home\model\UserAddress;
use app\home\model\UserCommission;
use app\home\model\UserCoupon;
use app\home\model\UserPackage;
use app\merchant\model\GoodsClassify;
use app\merchant\model\PayAmount;
use app\merchant\model\Store;
use app\merchant\model\UserConsumption;
use app\Request;
use app\services\wechat\Offiaccount;
use think\Exception;


class Order
{

    public function createGoodsOrder(Request $request)
    {
        $param = $request->param();
        $returnDate = [];
        $goodsModel = new \app\merchant\model\Goods();
        $goodsInfo = $goodsModel->where(['id' => $param['goods_id']])->find();
        if ($goodsInfo && $goodsInfo['inventory'] <= 0) {
            return error('商品缺货');
        }
        $data = [
            'goods_id' => $param['goods_id'],
            'pay_way' => $param['pay_way'],
            'remark' => $param['remark'],
            'take_over_way' => $param['take_over_way'],
            'number' => $param['number'],
            'sn_order' => getOrderNo('shop_'),
            'user_id' => $request->userInfo['id'],
            'total_price' => bcmul($param['number'], $goodsInfo['price'], 2), // 商品总价
            'reality_amount' => bcmul($param['number'], $goodsInfo['price'], 2),
            'status' => 1,
            'coupon_deduction_amount' => 0,
            'goods_name' => $goodsInfo['name'],
            'point_deduction_amount' => 0,
            'get_integral' => 0,
            'get_integral_ratio' => 0,
            'create_time' => time(),
            'update_time' => time(),
        ];
        if ($param['pay_way'] == 2 && $data['reality_amount'] > 0) {
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $data['pay_destination'] = 2;
            } else {
                $data['pay_destination'] = 3;
            }

        }
        if ($param['take_over_way'] == 1) {
            if (!isset($param['store_id']) || empty($param['store_id'])) {
                return error('请选择门店');
            }
            $data['store_id'] = $param['store_id'];
            $data['rand_code'] = createNonceStr(6);
        } else {
            if (!isset($param['address_id']) || empty($param['address_id'])) {
                return error('请选择收货地址');
            }
            $data['address_id'] = $param['address_id'];
        }
        // 商品折扣
        $goodsDiscountModel = new GoodsDiscount();
        $goodsDiscountInfo = $goodsDiscountModel->goodsLevelDiscount($request->userInfo['level_id'], $param['goods_id']);
        if (!empty($goodsDiscountInfo) && $goodsDiscountInfo['discount'] > 0) {  // 针对商品设置了 折扣
            $data['reality_amount'] = bcdiv(bcmul($data['reality_amount'], $goodsDiscountInfo['discount'], 2), 100, 2);
            $data['discount_ratio'] = $goodsDiscountInfo['discount'];
            $data['discount_type'] = 1;
        } else {
            $levelModel = new Level();
            $levelInfo = $levelModel->where(['id' => $request->userInfo['level_id']])->find();
            if ($levelInfo['shopping_preferential'] > 0) { // 针对商城全局的折扣
                $data['reality_amount'] = bcdiv(bcmul($data['reality_amount'], $levelInfo['shopping_preferential'], 2), 100, 2);
                $data['discount_ratio'] = $levelInfo['shopping_preferential'];
                $data['discount_type'] = 2;
            } else {
                if ($levelInfo['preferential'] > 0) {  // 全局的折扣
                    $data['reality_amount'] = bcdiv(bcmul($data['reality_amount'], $levelInfo['preferential'], 2), 100, 2);
                    $data['discount_ratio'] = $levelInfo['preferential'];
                    $data['discount_type'] = 3;
                }
            }
        }
        $data['discount_amount'] = bcsub($data['total_price'], $data['reality_amount'], 2);
        if (isset($param['coupon_id']) && !empty($param['coupon_id'])) {
            $userCouponModel = new UserCoupon();
            $coupon = $userCouponModel->where(['id' => $param['coupon_id']])->find();
            if ($coupon['status'] != 1 || $coupon['effective_time'] < time()) {
                return error('优惠券已失效');
            }
            if ($coupon['classify_id'] != 0) {
                if ($goodsInfo['classify_id'] != $coupon['classify_id']) {
                    $classModel = new GoodsClassify();
                    $class = $classModel->where(['id' => $goodsInfo['classify_id']])->find();
                    return error('此优惠券不能用于' . $class['name'] . '产品');
                }
            }
            $data['coupon_id'] = $coupon['coupon_id'];
            $data['user_coupon_id'] = $param['coupon_id'];// 用户的优惠券id
            if ($coupon['trigger_amount'] != 0 && $data['total_price'] < $coupon['trigger_amount']) {
                return error('订单价格未达到' . $coupon['trigger_amount']);
            }
            if ($data['reality_amount'] >= $coupon['discount_intensity']) {
                $data['reality_amount'] = bcsub($data['reality_amount'], $coupon['discount_intensity'], 2);
                $data['coupon_deduction_amount'] = $coupon['discount_intensity'];
            } else {
                $data['coupon_deduction_amount'] = $data['reality_amount'];
                $data['reality_amount'] = 0;
            }
        }
        if (isset($param['points_offset']) && $param['points_offset'] == 1) {
            if ($goodsInfo['buying_pattern'] == 1) {
                if ($data['reality_amount'] > 0) {
                    $ConfigModel = new Config();
                    $deductionRatio = $ConfigModel::getConfigValue('deduction_integral_ratio');
                    // 用户可抵扣金额
                    if ($deductionRatio) {
                        $userIntegralAmount = bcdiv($request->userInfo['surplus_integral'], $deductionRatio, 2);
                        if ($userIntegralAmount > 0) { // 用户有可以抵现的积分
                            if ($userIntegralAmount >= $data['reality_amount']) {
                                $data['point_deduction_ratio'] = $deductionRatio;
                                $data['point_deduction_amount'] = $data['reality_amount'];
                                $data['reality_amount'] = 0;
                            } else {
                                $data['point_deduction_ratio'] = $deductionRatio;
                                $data['point_deduction_amount'] = $userIntegralAmount;
                                $data['reality_amount'] = bcsub($data['reality_amount'], $data['point_deduction_amount'], 2);
                            }
                        }
                    }
                }
            } else {
                return error('此商品不允许积分抵现');
            }
        }
        $consumptionIntegralRatio = Config::getConfigValue('consumption_integral_ratio');
        $integral = bcmul($consumptionIntegralRatio, $data['reality_amount'], 2);

        if ($request->userInfo['birthday']) {
            $dateTime = date('Y-m-d', time());
            if ($request->userInfo['birthday'] == $dateTime) {
                $integral = bcmul($integral, 2, 2);
            }
        }
        $data['get_integral'] = $integral;
        $data['get_integral_ratio'] = $consumptionIntegralRatio;
        if ($param['pay_way'] == 1) {
            if ($request->userInfo['balance'] < $data['reality_amount']) {
                return error('用户余额不足');
            }
        }
        if ($param['pay_way'] == 2) {
            if ($data['reality_amount'] == 0) {
                $data['reality_amount'] = 0.01;
                $data['get_integral'] = 0;
                $data['get_integral_ratio'] = 0;
            }
        }
        try {
            $userModel = new \app\home\model\User();
            $orderModel = new GoodsOrder();
            $orderModel->insert($data);//
            $orderId = $orderModel->getLastInsID();
            $orderModel->startTrans();
            // 使用优惠券
            if ($data['coupon_deduction_amount'] > 0) {//优惠券有效
                $userCouponModel->where(['id' => $param['coupon_id']])->update(['status' => 3, 'update_time' => time()]); // 使用记录
                $couponModel = new \app\home\model\Coupon();
                $couponModel->where(['id' => $coupon['coupon_id']])->inc('use_number')->update(); // 使用次数
                $userModel->where(['id' => $request->userInfo['id']])->dec('coupon_num')->update();
            }
            // 使用积分
            if ($data['point_deduction_amount'] > 0) {  // 使用积分抵现
                $IntegralLogModel = new IntegralLog();
                $userNeedIntegralData = [
                    'mode_type' => 1,
                    'type' => 2,
                    'deduction_ratio' => $data['point_deduction_ratio'],
                    'num' => bcmul($data['point_deduction_amount'], $data['point_deduction_ratio'], 2),
                    'uid' => $request->userInfo['id'],
                    'create_time' => time(),
                    'order_id' => $orderId
                ];
                $IntegralLogModel->insert($userNeedIntegralData); //
                $userModel->where(['id' => $request->userInfo['id']])->dec('surplus_integral', $userNeedIntegralData['num'])->update();
            }
            $goodsModel->where(['id' => $param['goods_id']])->dec('inventory')->update();
            if ($param['pay_way'] == 1) {
                if ($data['reality_amount'] <= 0) {
                    // 优惠券加积分抵扣 已经可以购买了， 订单如果是自提需要去门店核销，如果是送货上门需要用确认收货
                    if ($param['take_over_way'] == 2) {  ///这里订单 已经购买成功了，消息该发送就发送了
                        $orderModel->where(['id' => $orderId])->update(['status' => 3, 'update_time' => time()]);
                    } else {
                        $orderModel->where(['id' => $orderId])->update(['status' => 4, 'update_time' => time()]);
                    }
                    $orderModel->commit();
                    $messageModel = new MessageTemplate();
                    if ($data['point_deduction_amount'] > 0) { // 使用了积分
                        $messageModel->sendMessage($request->userInfo['openid'], [
                            'phrase9' => ['value' => '积分'],
                            'thing2' => ['value' => '购买商品'],
                            'amount3' => ['value' => $userNeedIntegralData['num']],
                            'time6' => ['value' => date('Y-m-d H:i:s')]], 'integral_sub'); //
                    }
                    $messageModel->sendMessage($request->userInfo['openid'], [
                        'thing3' => ['value' => substr($goodsInfo['name'], 0, 18)],
                        'amount5' => ['value' => $data['reality_amount']],
                        'thing6' => ['value' => '无需支付金额'],
                        'time17' => ['value' => date('Y-m-d H:i')]], 'buy_goods');

                    return success('购买成功', []);
                }
                if ($request->userInfo['balance'] < $data['reality_amount']) {
                    $orderModel->rollback();
                    return error('用户余额不足');
                }
                $AmountLogData = [  // 金额扣除记录inc
                    'uid' => $request->userInfo['id'],
                    'amount' => $data['reality_amount'],
                    'create_time' => time(),
                    'operate_type' => 9,
                    'pay_type' => 4,
                    'pay_method' => 4,
                    'order_id' => $orderId,
                    'order_sn' => $data['sn_order'],
                    'ratio' => 1,
                    'type' => 2,
                    'status' => 0,
                ];
                $amountLogModel = new AmountLog();
                $amountLogModel->insert($AmountLogData);
                $userModel->where(['id' => $request->userInfo['id']])
                    ->dec('balance', $data['reality_amount'])
                    ->update();
                if ($param['take_over_way'] == 2) {
                    $orderModel->where(['id' => $orderId])->update(['status' => 3, 'update_time' => time()]);
                } else {
                    $orderModel->where(['id' => $orderId])->update(['status' => 4, 'update_time' => time()]);
                }
            }
            $orderModel->commit();
            if ($param['pay_way'] == 2) {
                $pay_type = Config::getConfigValue('pay_type');
                if ($pay_type == 1) {
                    $Offiaccount = new Offiaccount();
                    $WechatInfo = $Offiaccount->wechatpay($data, $request->userInfo['openid'], 'goodsNotify');
                } else {
                    $Offiaccount = new Offiaccount();
                    $WechatInfo = $Offiaccount->mWechatpay($data, $request->userInfo['openid'], 'goodsNotify');
                }
                if ($WechatInfo['code'] != 1) {
                    return error($WechatInfo['msg']);
                }
                $returnDate = $WechatInfo['data'];
            }
            $messageModel = new MessageTemplate();
            if ($data['point_deduction_amount'] > 0) { // 使用了积分
                $messageModel->sendMessage($request->userInfo['openid'], [
                    'phrase9' => ['value' => '积分'],
                    'thing2' => ['value' => '购买商品'],
                    'number3' => ['value' => $userNeedIntegralData['num']],
                    'time6' => ['value' => date('Y-m-d H:i:s')]], 'integral_sub'); //
            }
            $name ='微信支付';
            if ($param['pay_way'] == 1) {
                $messageModel->sendMessage($request->userInfo['openid'], [
                    'thing6' => ['value' => substr($goodsInfo['name'], 0, 18)],
                    'amount2' => ['value' => $data['reality_amount']],
                    'amount4' => ['value' => bcsub($request->userInfo['balance'], $data['reality_amount'], 2)],
                    'time1' => ['value' => date('Y-m-d H:i:s')]
                ], 'balance_sub');
                $name = '余额支付';
            }

            if ($request->userInfo['phone']) {
                $messageModel->sendAliMessage($request->userInfo['phone'], 'balance_sub', [
                    'platform' => Config::getConfigValue('system_name'),
                    'name' => $goodsInfo['name'],
                    'money' => $data['reality_amount'],
                ]);;
            }

            $messageModel->sendMessage($request->userInfo['openid'], [
                'thing3' => ['value' => substr($goodsInfo['name'], 0, 18)],
                'amount5' => ['value' => $data['reality_amount']],
                'thing6' => ['value' => $name],
                'time17' => ['value' => date('Y-m-d H:i')]], 'buy_goods'); // 购买商品

        } catch (Exception $exception) {
            $orderModel->rollback();
            return error($exception->getMessage() . '---' . $exception->getLine() . '---' . $exception->getFile());
        }
        return success('购买成功', $returnDate);
    }

    public function createPackageOrder(Request $request)
    {
        $param = $request->param();
        $packageModel = new \app\home\model\Package();
        $packageInfo = $packageModel->where(['id' => $param['id']])->find();
        if (empty($packageInfo)) {
            return error('套餐卡不存在');
        }
        $data = [
            'uid' => $request->userInfo['id'],
            'order_sn' => getOrderNo('pa_'),
            'package_id' => $param['id'],
            'price' => $packageInfo['price'],
            'create_time' => time(),
            'status' => 1,
            'pay_type' => $param['pay_way'],
            'original_price' => $packageInfo['price'],
            'get_integral' => 0,
            'get_integral_ratio' => 0,
            'number' => $packageInfo['number'],
            'give_number' => $packageInfo['give_number'],
        ];
        if ($param['pay_way'] == 2) {
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $data['pay_destination'] = 2;
            } else {
                $data['pay_destination'] = 3;
            }

            }
        $levelModel = new \app\merchant\model\Level();
        $levelInfo = $levelModel->where(['id' => $request->userInfo['level_id']])->find();
        if ($levelInfo['package_preferential'] > 0) { // 针对商城全局的折扣
            $data['price'] = bcdiv(bcmul($data['price'], $levelInfo['package_preferential'], 2), 100, 2);
            $data['discount_ratio'] = $levelInfo['package_preferential'];
            $data['discount_type'] = 2;
        } else {
            if ($levelInfo['preferential'] > 0) {  // 全局的折扣
                $data['price'] = bcdiv(bcmul($data['price'], $levelInfo['preferential'], 2), 100, 2);
                $data['discount_ratio'] = $levelInfo['preferential'];
                $data['discount_type'] = 3;
            }
        }
        $consumptionIntegralRatio = Config::getConfigValue('consumption_integral_ratio');
        $integral = bcmul($consumptionIntegralRatio, $data['price'], 2);
        if ($request->userInfo['birthday']) {
            $dateTime = date('Y-m-d', time());
            if ($request->userInfo['birthday'] == $dateTime) {
                $integral = bcmul($integral, 2, 2);
            }
        }
        $data['get_integral'] = $integral;
        $data['get_integral_ratio'] = $consumptionIntegralRatio;
        $packageOrderModel = new PackageOrder();
        $packageOrderModel->insert($data);
        $orderId = $packageOrderModel->getLastInsID();
        if ($param['pay_way'] == 2) {
            $data['sn_order'] = $data['order_sn']; // 统一下单接口 参数转换
            $data['reality_amount'] = $data['price'];
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $Offiaccount = new Offiaccount();
                $WechatInfo = $Offiaccount->wechatpay($data, $request->userInfo['openid'], 'packageNotify');
            } else {
                $Offiaccount = new Offiaccount();
                $WechatInfo = $Offiaccount->mWechatpay($data, $request->userInfo['openid'], 'packageNotify');
            }
            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error('失败', $WechatInfo['msg']);
            }
        } else {
            if ($request->userInfo['balance'] < $data['price']) {
                return error('余额不足');
            }
            try {
                $integralLogModel = new IntegralLog();
                $userModel = new \app\home\model\User();
                $userModel->startTrans();
                $distribution_level = Config::getConfigValue('distribution_level');
                $firstCommissionData = [];
                $secondCommissionData = [];
                if ($distribution_level > 0) {
                    if ($request->userInfo['pid'] > 0) {
                        $first_commission = Config::getConfigValue('first_commission');
                        if ($first_commission > 0) {
                            $pUserInfo = $userModel->where(['id' => $request->userInfo['pid']])->find();
                            $userCommissionModel = new UserCommission();
                            $firstCommissionData = [
                                'trigger_uid' => $request->userInfo['id'],
                                'receive_uid' => $request->userInfo['pid'],
                                'level' => 1,
                                'amount' => bcdiv(bcmul($data['price'], $first_commission, 2), 100, 2),
                                'ratio' => $first_commission,
                                'order_id' => $orderId,
                                'create_time' => time(),
                                'type' => 2,
                            ];
                            $userCommissionModel->insert($firstCommissionData);
                            $userModel->where(['id' => $request->userInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($first_commission, $data['price'], 2), 100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($first_commission, $data['price'], 2), 100, 2))
                                ->update();
                        }
                        if ($distribution_level >= 2) {
                            $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                            $second_commission = Config::getConfigValue('second_commission');

                            if ($second_commission > 0 && $pUserInfo['pid'] > 0) {
                                $userCommissionModel = new UserCommission();
                                $secondCommissionData = [
                                    'trigger_uid' => $request->userInfo['id'],
                                    'receive_uid' => $pUserInfo['pid'],
                                    'level' => 2,
                                    'amount' => bcdiv(bcmul($data['price'], $second_commission, 2), 100, 2),
                                    'ratio' => $second_commission,
                                    'order_id' => $orderId,
                                    'create_time' => time(),
                                    'type' => 2,
                                ];
                                $userCommissionModel->insert($secondCommissionData);
                                $userModel->where(['id' => $pUserInfo['pid']])
                                    ->inc('total_commission', bcdiv(bcmul($second_commission, $data['price'], 2), 100, 2))
                                    ->inc('surplus_commission', bcdiv(bcmul($second_commission, $data['price'], 2), 100, 2))
                                    ->update();
                            }
                        }
                    }
                }
                $userModel->where(['id' => $request->userInfo['id']])
                    ->inc('consumption_amount', $data['price'])
                    ->inc('package_num')
                    ->dec('balance', $data['price'])
                    ->inc('integral', $integral)
                    ->inc('surplus_integral', $integral)
                    ->update();
                $userModel->updateUserLevel($request->userInfo['id'], bcadd($request->userInfo['consumption_amount'], $data['price'], 2));
                if ($integral > 0) {
                    $integralLogData = [ // 积分变化
                        'num' => $integral,
                        'deduction_ratio' => $consumptionIntegralRatio,
                        'type' => 1,
                        'mode_type' => 5,
                        'order_id' => $orderId,
                        'create_time' => time(),
                        'uid' => $request->userInfo['id'],
                    ];
                    $integralLogModel->insert($integralLogData);
                }
                $amountLogModel = new  AmountLog(); // 支付记录
                $amountLogData = [
                    'uid' => $request->userInfo['id'],
                    'amount' => $data['price'],
                    'create_time' => time(),
                    'order_id' => $orderId,
                    'pay_method' => 4,
                    'operate_type' => 11,
                    'pay_type' => 4,
                    'ratio' => 1,
                    'type' => 2,
                    'order_sn' => $data['order_sn'],
                ];
                $amountLogModel->insert($amountLogData);
                $userPackageModel = new UserPackage();
                $userPackageData = [
                    'package_id' => $param['id'],
                    'uid' => $request->userInfo['id'],
                    'num' => $packageInfo['number'] + $packageInfo['give_number'],
                    'total_num' => $packageInfo['number'] + $packageInfo['give_number'],
                    'create_time' => time(),
                    'order_id' => $orderId,
                ];
                $userPackageModel->insert($userPackageData);
                $packageOrderModel->where(['id' => $orderId])->update([
                    'status' => 3,
                    'update_time' => time(),
                    'pay_time' => time(),
                ]);
                $packageModel->where(['id' => $param['id']])->inc('sales_volume')->inc('sales_amount', $packageInfo['price'])->update();
                $userModel->commit();


            } catch (Exception $exception) {
                $userModel->rollback();
                return error($exception->getMessage());
            }
        }
        $messageModel = new MessageTemplate();
        if ($firstCommissionData) { // 一级分佣
            $messageModel->sendMessage($pUserInfo['openid'], [
                'thing2' => ['value' => '直推佣金'],
                'amount8' => ['value' => $firstCommissionData['amount']],
                'amount6' => ['value' => bcadd($pUserInfo['surplus_commission'], $firstCommissionData['amount'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
        }
        if ($secondCommissionData) { // 一级分佣
            $messageModel->sendMessage($ppUserInfo['openid'], [
                'thing2' => ['value' => '间推佣金'],
                'amount8' => ['value' => $secondCommissionData['amount']],
                'amount6' => ['value' => bcadd($ppUserInfo['surplus_commission'], $secondCommissionData['amount'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')],
            ], 'commission_add'); //
        }
        $messageModel->sendMessage($request->userInfo['openid'], [
            'thing6' => ['value' => substr($packageInfo['name'], 0, 18)],
            'amount2' => ['value' => $data['price']],
            'amount4' => ['value' => bcsub($request->userInfo['balance'], $data['price'], 2)],
            'time1' => ['value' => date('Y-m-d H:i:s')]
        ], 'balance_sub'); // 余额变动
        $messageModel = new MessageTemplate();
        if ($request->userInfo['phone']) {
            $messageModel->sendAliMessage($request->userInfo['phone'], 'balance_sub', [
                'platform' => Config::getConfigValue('system_name'),
                'name' => $packageInfo['name'],
                'money' => $data['price'],
            ]);;
        }

        if ($integral > 0) {  // 添加积分
            $messageModel->sendMessage($request->userInfo['openid'], [
                'thing2' => ['value' => '积分'],
                'amount8' => ['value' => $integral . '分'],
                'amount6' => ['value' => bcadd($request->userInfo['surplus_integral'], $integral, 2) . '分'],
                'time4' => ['value' => date('Y-m-d H:i')]
            ], 'integral_add'); //
        }
        $messageModel->sendMessage($request->userInfo['openid'], [
            'thing2' => ['value' => $packageInfo['name']],
            'amount3' => ['value' => $packageInfo['price']],
            'thing9' => ['value' => date('Y-m-d  H:i:s')],
        ], 'buy_package'); // 购买套餐卡

        return success('购买成功');
    }

    public function rechargeOrder(Request $request)
    {
        $param = $request->param();
        $payAmount = new PayAmount();
        $payAmountConfig = $payAmount
            ->where('amount', '<=', $param['amount'])
            ->order('amount', 'desc')
            ->where(['status' => 1])->find();

        $data = [
            'uid' => $request->userInfo['id'],
            'sn_order' => getOrderNo('re_'),
            'amount' => $param['amount'],
            'create_time' => time(),
            'status' => 1,
            'type' => 1,
            'total_amount' => $param['amount'],
        ];

        $pay_type = Config::getConfigValue('pay_type');
        if ($pay_type == 1) {
            $data['pay_destination'] = 2;
        } else {
            $data['pay_destination'] = 3;
        }


        if ($payAmountConfig) {
            $data['total_amount'] = $param['amount'] + $payAmountConfig['give_amount'];
            $data['give_amount'] = $payAmountConfig['give_amount'];
        }
        $rechargeModel = new Recharge();
        $rechargeModel->insert($data);
        $Offiaccount = new Offiaccount();
        $data['reality_amount'] = $param['amount'];
        if ($pay_type == 1) {
            $Offiaccount = new Offiaccount();
            $WechatInfo = $Offiaccount->wechatpay($data, $request->userInfo['openid'], 'rechargeNotify');
        } else {
            $Offiaccount = new Offiaccount();
            $WechatInfo = $Offiaccount->mWechatpay($data, $request->userInfo['openid'], 'rechargeNotify');
        }
        if ($WechatInfo['code'] == 1) {
            return success('成功', $WechatInfo['data']);
        } else {
            return error('失败', $WechatInfo['msg']);
        }

    }

    public function goodsOrderList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where['user_id'] = $request->userInfo['id'];
        if (isset($param['status']) && !empty($param['status'])) {
            $where['status'] = $param['status'];
        }
        $goodsOrderModel = new GoodsOrder();
        if (isset($param['order_name']) && !empty($param['order_name'])) {
            $list = $goodsOrderModel->where($where)
                ->where('goods_name|sn_order', 'like', '%' . $param['order_name'] . '%')
                ->limit($start, $limit)
                ->order('create_time', 'desc')
                ->select()->toArray();
            $count = $goodsOrderModel->where($where)->where('goods_name|sn_order', 'like', '%', $param['order_name'] . '%')->count();
        } else {
            $list = $goodsOrderModel->where($where)
                ->limit($start, $limit)
                ->order('create_time', 'desc')
                ->select()->toArray();
            $count = $goodsOrderModel->where($where)->count();
        }

        if ($list) {
            $goodsId = array_column($list, 'goods_id');
            $goodsModel = new \app\merchant\model\Goods();
            $goodsList = $goodsModel->where('id', 'in', $goodsId)->field('id,name,host_img,title')->select()->toArray();
            $goodsListById = array_column($goodsList, null, 'id');
            foreach ($list as $key => $value) {
                $list[$key]['goods_name'] = $goodsListById[$value['goods_id']]['name'];
                $list[$key]['host_img'] = $goodsListById[$value['goods_id']]['host_img'];
                $list[$key]['title'] = $goodsListById[$value['goods_id']]['title'];
            }

        }
        return success('商城订单列表', ['list' => $list, 'count' => $count]);
    }

    public function goodsOrderInfo(Request $request)
    {
        $param = $request->param();
        $goodsOrderModel = new GoodsOrder();
        $info = $goodsOrderModel->where(['id' => $param]['id'])->find();
        if ($info['address_id']) {
            $addressModel = new UserAddress();
            $addressInfo = $addressModel->where(['id' => $info['address_id']])->find();
            $info['address_province_name'] = $addressInfo['province_name'];
            $info['address_city_name'] = $addressInfo['city_name'];
            $info['address_county_name'] = $addressInfo['county_name'];
            $info ['address'] = $addressInfo['address'];
            $info['address_phone'] = $addressInfo['phone'];
            $info['address_name'] = $addressInfo['name'];
        } else {
            $info['address_province_name'] = '';
            $info['address_city_name'] = '';
            $info['address_county_name'] = '';
            $info ['address'] = '';
            $info['address_phone'] = '';
            $info['address_name'] = '';
        }
        if ($info['coupon_id']) {
            $couponModel = new \app\home\model\Coupon();
            $couponInfo = $couponModel->where(['id' => $info['coupon_id']])->find();
            $info['coupon_name'] = $couponInfo['name'];
            $info['trigger_amount'] = $couponInfo['trigger_amount'];
            $info['discount_intensity'] = $couponInfo['discount_intensity'];
        } else {
            $info['coupon_name'] = '';
            $info['trigger_amount'] = '';
            $info['discount_intensity'] = '';
        }
        if ($info['store_id']) {
            $storeModel = new Store();
            $storeInfo = $storeModel->where(['id' => $info['store_id']])->find();
            $info['store_name'] = $storeInfo['name'];
            $info['store_province_name'] = $storeInfo['province_name'];
            $info['store_city_name'] = $storeInfo['city_name'];
            $info['store_county_name'] = $storeInfo['county_name'];
            $info['store_address'] = $storeInfo['address'];
            $info['store_phone'] = $storeInfo['phone'];
            $info['store_real_name'] = $storeInfo['real_name'];
        } else {
            $info['store_name'] = '';
            $info['store_province_name'] = '';
            $info['store_city_name'] = '';
            $info['store_county_name'] = '';
            $info['store_address'] = '';
            $info['store_phone'] = '';
            $info['store_real_name'] = '';
        }
        $goodsModel = new \app\merchant\model\Goods();
        $goodsInfo = $goodsModel->where(['id' => $info['goods_id']])->find();
        $info['goods_desc'] = $goodsInfo['desc'];
        $info['goods_price'] = $goodsInfo['price'];
        $info['title'] = $goodsInfo['title'];
        return success('订单详情', $info);
    }

    public function packageOrderList(Request $request)
    {
        $packageOrderModel = new PackageOrder();
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['stats']) && !empty($param['stats'])) {
            $where[] = ['status', '=', $param['status']];
        } else {
            $where[] = ['status', 'in', [2, 3]];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['uid', '=', $request->userInfo['id']];
        $list = $packageOrderModel->where($where)->limit($start, $limit)->select()->toArray();
        $count = $packageOrderModel->where($where)->limit($start, $limit)->select()->toArray();
        if ($list) {
            $packageId = array_column($list, 'package_id');
            $orderId = array_column($list, 'id');
            $packageModel = new \app\home\model\Package();
            $packageArray = $packageModel->where('id', 'in', $packageId)->select()->toArray();
            $packageUser = new UserPackage();
            $packageUserList = $packageUser->where('order_id', 'in', $orderId)->select()->toArray();
            $orderByPackage = array_column($packageUserList, null, 'order_id');
            $packageById = array_column($packageArray, null, 'id');
            foreach ($list as $key => $value) {
                $list[$key]['package_name'] = $packageById[$value['package_id']]['name'];
                $list[$key]['package_desc'] = $packageById[$value['package_id']]['desc'];
                $list[$key]['num'] = $orderByPackage[$value['id']]['num'];
                $list[$key]['use_num'] = $orderByPackage[$value['id']]['total_num'] - $orderByPackage[$value['id']]['num'];
            }
        }
        return success('套餐卡订单列表', ['list' => $list, 'count' => $count]);
    }

    public function rechargeOrderList(Request $request)
    {
        $param = $request->param();
        $rechargeModel = new Recharge();
        $limit = 10;
        $start = 0;
        if (isset($param['stats']) && !empty($param['stats'])) {
            $where[] = ['status', '=', $param['status']];
        } else {
            $where[] = ['status', 'in', [1, 2, 3]];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['sn_order']) && !empty($param['sn_order'])) {
            $where[] = ['sn_order', '=', $param['sn_order']];
        }
        $where['uid'] = $request->userInfo['id'];
        $list = $rechargeModel->where($where)->limit($start, $limit)->order('create_time','desc')->select()->toArray();
        $count = $rechargeModel->where($where)->count();
        return success('充值列表', ['list' => $list, 'count' => $count]);
    }

    /*  public function confirmOrder(Request $request)
      {
          $param = $request->param();
          $goodsOrderModel = new GoodsOrder();
          $goodsOrderModel->where(['id' => $param['id']])->update(['status' => 6]);
          return success('操作成功');
      }*/
    public function amountLog(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $amountModel = new AmountLog();
        $amountList = $amountModel->where(['uid' => $request->userInfo['id']])
            ->limit($start, $limit)->select()->toArray();
        $count = $amountModel->where(['uid' => $request->userInfo['id']])->count();
        return success('营收记录', ['list' => $amountList, 'count' => $count]);
    }

    public function applyReturns(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $goodsOrder = new GoodsOrder();
        $goodsInfo = $goodsOrder->where(['id' => $id])->find();
        if ($goodsInfo['status'] != 1 || $goodsInfo['status'] != 7 || $goodsInfo['status'] != 6) {
            $goodsOrder->where(['id' => $id])->update(['status' => 5]);
            return success('申请成功,等待商家确认');
        }
    }

    public function completeGoodsOrder(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $goodsOrder = new GoodsOrder();
        $goodsOrderInfo = $goodsOrder->where(['id' => $id])->find();
        $goodsOrder->where(['id' => $id])->update(['status' => 6]);
        $userModel = new \app\home\model\User();
        try {
            $userModel->startTrans();

            $integral = 0;
            $firstCommissionData = [];
            $secondCommissionData = [];
            if ($goodsOrderInfo['total_price'] > $goodsOrderInfo['point_deduction_amount']) { //积分全部抵扣了订单金额选择微信付款需要支付 0.01
                $integral = $goodsOrderInfo['get_integral'];
                $userAddIntegralData = [  // 添加用户积分
                    'mode_type' => 4,
                    'type' => 1,
                    'deduction_ratio' => $goodsOrderInfo['get_integral_ratio'],
                    'num' => $integral,
                    'uid' => $request->userInfo['id'],
                    'create_time' => time(),
                    'order_id' => $goodsOrderInfo['id']
                ];
                if ($userAddIntegralData['num'] > 0) {
                    $IntegralLogModel = new IntegralLog();
                    $IntegralLogModel->insert($userAddIntegralData);
                }
                $distribution_level = Config::getConfigValue('distribution_level');
                if ($distribution_level > 0) { // 分佣
                    if ($request->userInfo['pid'] > 0) {
                        $first_commission = Config::getConfigValue('first_commission');
                        if ($first_commission > 0) {
                            $pUserInfo = $userModel->where(['id' => $request->userInfo['pid']])->find();
                            $userCommissionModel = new UserCommission();
                            $firstCommissionData = [
                                'trigger_uid' => $request->userInfo['id'],
                                'receive_uid' => $request->userInfo['pid'],
                                'level' => 1,
                                'amount' => bcdiv(bcmul($goodsOrderInfo['reality_amount'], $first_commission, 2), 100, 2),
                                'ratio' => $first_commission,
                                'order_id' => $goodsOrderInfo['id'],
                                'create_time' => time(),
                                'type' => 1,
                            ];
                            $userCommissionModel->insert($firstCommissionData);
                            $userModel->where(['id' => $request->userInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($first_commission, $goodsOrderInfo['reality_amount'], 2), 100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($first_commission, $goodsOrderInfo['reality_amount'], 2), 100, 2))
                                ->update();
                        }
                        if ($distribution_level >= 2) {
                            $second_commission = Config::getConfigValue('second_commission');;
                            if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                                $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                                $userCommissionModel = new UserCommission();
                                $secondCommissionData = [
                                    'trigger_uid' => $request->userInfo['id'],
                                    'receive_uid' => $pUserInfo['pid'],
                                    'level' => 2,
                                    'amount' => bcdiv(bcmul($goodsOrderInfo['reality_amount'], $second_commission, 2), 100, 2),
                                    'ratio' => $second_commission,
                                    'order_id' => $goodsOrderInfo['id'],
                                    'create_time' => time(),
                                    'type' => 1,
                                ];
                                $userCommissionModel->insert($secondCommissionData);
                                $userModel->where(['id' => $pUserInfo['pid']])
                                    ->inc('total_commission', bcdiv(bcmul($second_commission, $goodsOrderInfo['reality_amount'], 2), 100, 2))
                                    ->inc('surplus_commission', bcdiv(bcmul($second_commission, $goodsOrderInfo['reality_amount'], 2), 100, 2))
                                    ->update();
                            }
                        }
                    }
                }
            }
            $userModel->where(['id' => $request->userInfo['id']])
                ->inc('integral', $integral)
                ->inc('surplus_integral', $integral)
                ->inc('consumption_amount', $goodsOrderInfo['reality_amount'])
                ->update();
            $userModel->updateUserLevel($request->userInfo['id'], bcadd($request->userInfo['consumption_amount'], $goodsOrderInfo['reality_amount'], 2));
            $amountLog = new AmountLog();
            if ($goodsOrderInfo['store_id']> 0){
                $storeModel = new \app\merchant\model\Store();
                $storeModel->where(['id' => $goodsOrderInfo['store_id']])->inc('goods_amount',$goodsOrderInfo['reality_amount'])->update();
            }
            $amountLog->where(['order_id' => $id, 'order_sn' => $goodsOrderInfo['sn_order']])->update(['status' => 1]);
            $userModel->commit();
        } catch (Exception $exception) {
            $userModel->rollback();
            $goodsOrder->where(['id' => $id])->update(['status' => 2]);
            return error($exception->getMessage());
        }
        $messageModel = new MessageTemplate();
        if ($integral > 0) {
            $messageModel->sendMessage($request->userInfo['openid'], [
                'thing2' => ['value' => '积分'],
                'amount8' => ['value' => $userAddIntegralData['num'] . '分'],
                'amount6' => ['value' => bcadd($request->userInfo['surplus_integral'], $userAddIntegralData['num'], 2) . '分'],
                'time4' => ['value' => date('Y-m-d H:i')]
            ], 'integral_add'); //
        }
        if ($firstCommissionData) { // 一级分佣
            $messageModel->sendMessage($pUserInfo['openid'], [
                'thing2' => ['value' => '直推佣金'],
                'amount8' => ['value' => $firstCommissionData['amount']],
                'amount6' => ['value' => bcadd($firstCommissionData['amount'], $pUserInfo['surplus_commission'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
        }
        if ($secondCommissionData) { // 一级分佣
            $messageModel->sendMessage($ppUserInfo['openid'], [
                'thing2' => ['value' => '间推佣金'],
                'amount8' => ['value' => $secondCommissionData['amount']],
                'amount6' => ['value' => bcadd($secondCommissionData['amount'], $ppUserInfo['surplus_commission'], 2)],
                'time4' => ['value' => date('Y-m-d H:i')],
            ], 'commission_add'); //
        }


        return success('操作成功');
    }

    public function cancelOrder(Request $request)
    {
        $param = $request->param();
        $goodsOrderModel = new GoodsOrder();
        $orderInfo = $goodsOrderModel->where(['id' => $param['id'], 'user_id' => $request->userInfo['id']])->find();
        if (empty($orderInfo)) {
            return error('订单有误');
        }
        $goodsOrderModel->where(['id' => $param['id'], 'user_id' => $request->userInfo['id']])->update(['status' => 8]);
        if ($orderInfo['status'] != 1) {
            return error('订单有误');
        }
        if ($orderInfo['point_deduction_amount'] > 0) {
            $userNeedIntegralData = [
                'mode_type' => 7,
                'type' => 1,
                'deduction_ratio' => $orderInfo['point_deduction_ratio'],
                'num' => bcmul($orderInfo['point_deduction_amount'], $orderInfo['point_deduction_ratio'], 2),
                'uid' => $request->userInfo['id'],
                'create_time' => time(),
                'order_id' => $param['id']
            ];
            $IntegralLogModel = new IntegralLog();
            $IntegralLogModel->insert($userNeedIntegralData); //
            $userModel = new \app\home\model\User();
            $userModel->where(['id' => $request->userInfo['id']])->inc('surplus_integral', $userNeedIntegralData['num']);
        }
        if ($orderInfo['user_coupon_id']) {
            $userCouponModel = new UserCoupon();
            $userCouponModel->where(['id' => $orderInfo['user_coupon_id']])->update(['status' => 1]);
            $couponModel = new \app\home\model\Coupon();
            $couponModel->where(['id' => $orderInfo['coupon_id']])->dec('use_number')->update(); //
            $userModel->where(['id' => $orderInfo['user_id']])->inc('coupon_num')->update();
        }
        if ($orderInfo['point_deduction_amount'] > 0) {
            $messageModel = new MessageTemplate();
            $messageModel->sendMessage($request->userInfo['openid'], [
                'thing2' => ['value' => '积分返还'],
                'amount8' => ['value' => $userNeedIntegralData['num'] . '分'],
                'amount6' => ['value' => bcadd($request->userInfo['surplus_integral'], $userNeedIntegralData['num'], 2) . '分'],
                'time4' => ['value' => date('Y-m-d H:i')]
            ], 'integral_add'); //
        }
        return success('操作成功');
    }

    public function payGoodsOrder(Request $request)
    {
        $param = $request->param();
        $goodsOrderModel = new GoodsOrder();
        $orderInfo = $goodsOrderModel->where(['id' => $param['id']])->find();
        if ($orderInfo['status'] != 1) {
            return adminError('订单有误');
        }
        $sn_order = getOrderNo('shop_');
        $goodsOrderModel->where(['id' => $param['id']])->update(['sn_order' => $sn_order]);
        if ($orderInfo['pay_way'] == 2) {
            $orderInfo['sn_order'] = $sn_order;
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $Offiaccount = new Offiaccount();
                $WechatInfo = $Offiaccount->wechatpay($orderInfo, $request->userInfo['openid'], 'goodsNotify');
            } else {
                $Offiaccount = new Offiaccount();
                $WechatInfo = $Offiaccount->mWechatpay($orderInfo, $request->userInfo['openid'], 'goodsNotify');
            }

            if ($WechatInfo['code'] == 1) {
                return success('成功', $WechatInfo['data']);
            } else {
                return error('失败', $WechatInfo['msg']);
            }
        }
    }

    public function polymerizationPay(Request $request){
        $param = $request->param();
        $data = [
            'original_price' => $param['amount'],
            'uid' => 0,
            'sn_order' => getOrderNo('cm_'),
            'store_id' =>  $param['store_id'],
            'create_time' => time(),
            'pay_status' => 1,
            'status' => 1,
            'update_time' => time(),
            'pay_type' =>  $param['pay_type'],
            'get_integral' => 0,
            'get_integral_ratio' => 0,
            'pay_destination' => 1,
            'discount_ratio' => 0,
            'is_polymerization' => 1,
            'amount' => $param['amount'],
        ];
        $payType = Config::getConfigValue('pay_type');

        if ($param['pay_type'] == 9){
            $Offiaccount =  new Offiaccount();
            $wechatInfo = $Offiaccount->getOauth2AccessToken( $param['code']);
            if (isset($wechatInfo['errcode'])){
                return error($wechatInfo['errmsg']);
            }
            $data['open_id'] = $wechatInfo['openid'];
        }
        if ($payType == 1){
            $data['pay_destination'] =  2;
        }else{
            $data['pay_destination'] =  3;
        }

        $user_consumptionModel = new UserConsumption();
        $user_consumptionModel->insert($data);
        if ($param['pay_type'] == 9){
            $Offiaccount =  new Offiaccount();
            $data['reality_amount'] = $param['amount'];
           if ($payType == 1){
               $WechatInfo = $Offiaccount->wechatpay($data, $data['open_id'] , 'polymerizationNotify');
           }else{
               $WechatInfo =  $Offiaccount->Mwechatpay($data, $data['open_id'] , 'polymerizationNotify');
           }
            if ($WechatInfo['code'] != 1) {
                return error($WechatInfo['msg']);
            }
            return success('用户付款中', $WechatInfo['data']);
        }else{
            $Offiaccount  = new \app\services\alipay\Offiaccount();
            $data['reality_amount'] = $param['amount'];
            $info = $Offiaccount->pay($data,Config::getConfigValue('system_name'),'alipolymerizationNotify');
            return success('用户付款中',$info);
        }


    }

    public function alipolymerizationNotify(){
        file_put_contents('./log/' . date('Y-m-d') . 'aliuserConsumption.txt', json_encode($_POST) . PHP_EOL, FILE_APPEND);
        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            $out_trade_no = $_POST['out_trade_no'];
            $UserConsumption = new  UserConsumption();
            $UserConsumptionInfo = $UserConsumption->where(['sn_order' => $out_trade_no])->find();
            if ($UserConsumptionInfo['status'] != 1){
                echo 'fail';
            }
            if ($UserConsumptionInfo['amount'] != $_POST['total_amount'] ){
                echo 'fail';
            }
            $UserConsumption->where(['sn_order' => $out_trade_no])->update(['status' => 2]);
            $UserConsumption->startTrans();
            $amountLog = new AmountLog();
            $amountLog->insert([
                'amount' => $UserConsumptionInfo['amount'],
                'pay_method' => 2,
                'order_id' => $UserConsumptionInfo['id'],
                'operate_type' => 28,
                'pay_type' => 5,
                'create_time' => time(),
                'ratio' => 1,
                'uid' => 0,
                'type' => 2,
                'order_sn' => $UserConsumptionInfo['sn_order'],
                'status' => 1,
                'store_id' => $UserConsumptionInfo['store_id'],
                'is_polymerization' => 1,
            ]);
            $UserConsumption->where(['sn_order' => $out_trade_no])->update(['status' => 3, 'update_time' => time()]);
            $UserConsumption->commit();
            echo 'success';exit;
        }
    }


}